import { Box, Typography,Button,TextField ,Dialog ,DialogActions ,DialogContent ,DialogContentText ,DialogTitle  } from '@mui/material';
import MessageContainer from 'components/digital/MessageContainer';
import DigtalButton from 'components/digital/DigtalButton';
import {
    IMessage,
    askUserState,
    messagesState,
    sessionState,
    loadingState,
    promtStringState,
    fullscreenState,
    openComfirmState
} from 'state/chat';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { useState, useCallback } from 'react'
import InputBox from 'components/organisms/chat/inputBox/input';
import { v4 as uuidv4 } from 'uuid';
import { useAuth } from 'hooks/auth';
import { chatHistoryState } from 'state/chatHistory';
import ChatbotIcon from 'assets/chatbot.png';
import DialogBg from 'assets/dialog-bg_03.png';
import yuanyuan from 'assets/yuanyuan.png';
import XiaoYuBg from 'assets/xiaoyu_bg.png';
import { toast } from 'react-hot-toast';

export default function ChatContainer() {
    const [messages, setMessages] = useRecoilState(messagesState)
    const session = useRecoilValue(sessionState)


    const setPromtString= useSetRecoilState(promtStringState);
    const [openComfirm,setopenComfirm] = useRecoilState(openComfirmState)
    const [fullscreen,setfullscreen] = useRecoilState(fullscreenState)
    const { user, isAuthenticated } = useAuth();
    const setChatHistory = useSetRecoilState(chatHistoryState);
    const [autoScroll, setAutoScroll] = useState(true);
    const askUser = useRecoilValue(askUserState);
    let [currInput,setCurrInput] = useState('');

    const onSubmit = useCallback(
        async (msg: string) => {
            const sessionId = session?.socket.id;

            if (!sessionId) {
                return;
            }

            const message: IMessage = {
                id: uuidv4(),
                author:'访客',
                authorIsUser: true,
                content: msg,
                createdAt: new Date().toISOString()
            };

            const message1: IMessage = {
                id: uuidv4(),
                author: '元晓宇',
                authorIsUser: false,
                content: msg,
                createdAt: new Date().toISOString()
            };

            setChatHistory((old) => {
                const MAX_SIZE = 50;
                const messages = [...(old.messages || [])];
                messages.push({
                    content: msg,
                    createdAt: new Date().getTime()
                });

                return {
                    ...old,
                    messages:
                        messages.length > MAX_SIZE
                            ? messages.slice(messages.length - MAX_SIZE)
                            : messages
                };
            });

            setAutoScroll(true);
            setMessages((oldMessages) => [...oldMessages, message]);
            setMessages((oldMessages) => [...oldMessages, message1]);
            session?.socket.emit('ui_message', message);
        },
        [user, session, isAuthenticated]
    );

    const onReply = useCallback(
        async (msg: string) => {
            if (!askUser) return;
            const message = {
                id: uuidv4(),
                author: '访客',
                authorIsUser: true,
                content: msg,
                createdAt: new Date().toISOString()
            };
            askUser.callback(message);

            setAutoScroll(true);
            setMessages((oldMessages) => [...oldMessages, message]);
        },
        [askUser, user]
    );

    const onSend1 = ()=>{
        setPromtString('介绍下你自己')

    }
    const onSend2 = ()=>{
        setPromtString('介绍下新建元')

    }
    const onSend3 = ()=>{
        setPromtString('介绍下新建元的资产规模')

    }
    const onSend4 = ()=>{
        setPromtString('新建元有哪些业务')

    }
    const onSend5 = ()=>{
        setPromtString('介绍下新建元数科')

    }
    const onSend6 = ()=>{
        setPromtString('介绍下新建元数科业务布局')


    }


         // 控制屏幕不能操作
         const onControll = ()=>{
            // 弹框确认
            handleClickOpen();


        }
        const handleClickOpen = () => {
            setopenComfirm(true);
        };

        const handleClose = () => {
            setopenComfirm(false);
            setCurrInput('')
            // if (reason !== 'backdropClick' && reason !== 'escapeKeyDown') {

            // }
        };
        const handleCommitCtrl = ()=>{
            if(currInput =='123456789'){
                // 调用机器人
                session?.socket.send(JSON.stringify({"msg_id":"CMD_OPEN_SYSTEM_SETTINGS"}));
                toast.success('操作成功')
                setopenComfirm(false);
                setCurrInput('')
            }else{
                toast.error('密码不正确')
            }
        }

        // 播放资料
        const onAlbum = ()=>{
            // 调用机器人
            session?.socket.send(JSON.stringify({"msg_id":"CMD_OPEN_SYSTEM_SETTINGS"}));
        }

        const inputTxt = (txt:any)=>{
        //    currInput =;
           setCurrInput(txt.target.value)
        }

        // 全屏
        const onFullScreen = ()=>{
            // 退出全屏
            if(fullscreen){
                // @ts-ignore
                if (document.exitFullscreen) {
                    // @ts-ignore
                    document.exitFullscreen();
                    // @ts-ignore
                  } else if (document.mozCancelFullScreen) { // Firefox
                    // @ts-ignore
                    document.mozCancelFullScreen();
                    // @ts-ignore
                  } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
                    // @ts-ignore
                    document.webkitExitFullscreen();
                    // @ts-ignore
                  } else if (document.msExitFullscreen) { // Internet Explorer and Edge
                    // @ts-ignore
                    document.msExitFullscreen();
                  }
                setfullscreen(false)
            // 全屏
            }else{
                // const element = document.getElementById('digitalBoxId');
                const element = document.body;
                // @ts-ignore
                if (element.requestFullscreen) {
                     // @ts-ignore
                element.requestFullscreen();
                 // @ts-ignore
                } else if (element.mozRequestFullScreen) { // Firefox
                     // @ts-ignore
                element.mozRequestFullScreen();
                 // @ts-ignore
                } else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera
                     // @ts-ignore
                element.webkitRequestFullscreen();
                 // @ts-ignore
                } else if (element.msRequestFullscreen) { // Internet Explorer and Edge
                // @ts-ignore
                element.msRequestFullscreen();
                }

                setfullscreen(true)

            }
        }







    // const handleClick = () => {
    //     setStatus('conversation')
    // }

    // setInterval(()=>{
    //     setMessages((s)=>{return [...s,{
    //         id: '12345678',
    //         author: '元晓宇',
    //         content: '你好，我是新建元数字员工元晓宇，请问有什么需要帮助的吗？',
    //         createdAt: new Date().toISOString(),
    //         type: 'welcome'
    //       }]})
    //  },5000)

    return (
        <Box sx={{
            position: 'relative',
            width: '94%',
            height: '85%',
            display: 'flex',
            flexDirection: 'column',
            borderRadius: '10px',
            // backgroundColor: 'rgba(255, 255, 255, 0.1)',
            backgroundImage: `url(${DialogBg})`,
            backgroundSize: '100% 100%',
            padding: '10px 10px 30px',
        }}>
            <Box className="header" display="flex" padding="50px 30px 30px" sx={{
              background: `url(${XiaoYuBg}) no-repeat left center`,
              'background-size': '98px 89px',
              'background-origin': 'content-box',

            }}>
                {/*<img style={{*/}
                {/*    position: 'absolute',*/}
                {/*    width: '98px',*/}
                {/*    height: '89px',*/}
                {/*    top: 24,*/}
                {/*    left: 13,*/}
                {/*    borderRadius: '50%'*/}
                {/*}} src={XiaoYuBg} />*/}
                <img style={{ width: '50px', height: '50px', marginRight: '30px', borderRadius: '50%','margin-left': '28px' }} src={yuanyuan} />
                <Box color="#E8E8E8" className="text" display="flex" flexDirection="column">
                    <span className="name" style={{fontSize: '23.4px', fontWeight: 500 }}>元元</span>
                    <span className="compony" style={{fontSize: '16.1px'}}>新建元控股集团</span>
                </Box>
            </Box>
            <Box sx={{
                 height: '1px',
                 width: '94%',
                 marginLeft: '3%',
                 backgroundColor: 'rgba(216,216,216,0.3)',
            }}></Box>
            {
                (
                    <MessageContainer
                        autoScroll={autoScroll}
                        setAutoScroll={setAutoScroll}
                        messages={messages}
                        elements={[]}
                        actions={[]}>
                    </MessageContainer>
                )
            }
            {/* 麦克风图标 */}
            <DigtalButton></DigtalButton>
             {/* <InputBox onReply={onReply} onSubmit={onSubmit} />  */}
                <div style={{display:'flex',alignItems:'flex-end',position:'absolute',bottom:'-30px',zIndex:'100'}}>
                    {/* <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend1} onClick={onSend1}>提问1</span>
                    <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend2} onClick={onSend2} >提问2</span>
                    <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend3} onClick={onSend3} >提问3</span>  */}
                    {/* <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend4} onClick={onSend4} >提问4</span>
                    <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend5} onClick={onSend5} >提问5</span>
                    <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onSend6} onClick={onSend6} >提问6</span> */}
                    {/* {
                        fullscreen ?
                        <img src='assets/single.png' alt='widthFix' style={{marginRight:'20px',zIndex:'100'}} onTouchStart ={onFullScreen}  onClick={onFullScreen} ></img>
                        :
                        <img src='assets/single1.png' alt='widthFix' style={{marginRight:'20px',zIndex:'100'}} onTouchStart ={onFullScreen}  onClick={onFullScreen} ></img>
                    } */}
                    {/* <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onControll} onClick={onControll} >控制</span> */}
                    {/* <span style={{color:'white',cursor:'pointer',marginLeft:'20px'}} onTouchStart={onAlbum} onClick={onAlbum} >播放资料</span> */}

                </div>


                  {/* 弹框确认 */}
                  {/* <Dialog
                    open={openComfirm}
                    onClose={handleClose}
                    PaperProps={{
                    component: 'form',
                    onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
                        event.preventDefault();
                        const formData = new FormData(event.currentTarget);
                        const formJson = Object.fromEntries((formData as any).entries());
                        const email = formJson.email;
                        console.log(email);
                        handleClose();
                    },
                    }}
                >
                    <DialogTitle>友情提示</DialogTitle>
                    <DialogContent>
                    <DialogContentText>
                       该操作比较危险，请先输入密码
                    </DialogContentText>
                    <TextField
                        autoFocus
                        required
                        margin="dense"
                        id="name"
                        name="psd"
                        label="密码"
                        type="password"
                        fullWidth
                        variant="standard"
                        onChange={inputTxt}
                    />
                    </DialogContent>
                    <DialogActions>
                    <Button onTouchStart={handleClose} onClick={handleClose}>取消</Button>
                    <Button type="submit" onTouchStart={handleCommitCtrl} onClick={handleCommitCtrl}>确认</Button>
                    </DialogActions>
                </Dialog> */}
{/* openComfirm */}
               <div style={{display:openComfirm?'block':'none',position:'fixed',zIndex:999999,background:'#00000055',top:'0',left:'0',width:'100vw',height:'100vh'}}
               >
                <div style={{background:'rgb(43 72 163)',borderRadius:"10px",width:'550px',margin:'30vh auto 0'}}>
                    <div style={{textAlign:'center',fontSize:'20px',lineHeight:'60px',color:'#fff'}}>友情提示</div>
                    <div style={{textAlign:'center',fontSize:'16px',lineHeight:'40px', color:'#eee'}}>该操作很危险，确认操作前请输入密码？</div>
                    <div style={{textAlign:'center',padding:'10px'}}>
                       <input value={currInput} onChange={inputTxt} style={{padding:'15px 0',width:'80%'}} type="password" placeholder='请输入密码'></input>
                    </div>
                    <div style={{display:'flex',justifyContent:'space-around',padding:'20px 80px'}}>
                        <div style={{color:'rgb(105 206 245)',border:'1px solid rgb(105 206 245)',borderRadius:'10px',width:'120px',height:'50px',lineHeight:'50px',background:'rgb(12 27 57)',textAlign:'center',cursor:'pointer'}} onTouchStart={handleClose} onClick={handleClose}>取消</div>
                        <div style={{color:'rgb(105 206 245)',border:'1px solid rgb(105 206 245)',borderRadius:'10px',width:'120px',height:'50px',lineHeight:'50px',background:'rgb(12 27 57)',textAlign:'center',cursor:'pointer'}} onTouchStart={handleCommitCtrl} onClick={handleCommitCtrl}>确认</div>
                    </div>
                </div>
               </div>

        </Box >
    );
}
